package czStvDpds.collisionGeometry;

/**
 * Polygonový hitbox
 *
 * @author Jirka
 */
public class PolygonHitBox {

    private int numVertices;
    private PointHitBox[] vertices;

    public PolygonHitBox(int buffer) {
        this.numVertices = 0;
        vertices = new PointHitBox[buffer];
    }

    /**
     * Defaultní buffer je 4
     */
    public PolygonHitBox() {
        this.numVertices = 0;
        vertices = new PointHitBox[4];
    }

    public int getNumVertices() {
        return numVertices;
    }

    public PointHitBox getVertex(int index) {
        if (index < numVertices) {
            return vertices[index];
        } else {
            return null;
        }
    }

    private void resize() {
        PointHitBox[] temp = new PointHitBox[2 * numVertices + 1];
        for (int i = 0; i <= numVertices; i++) {
            temp[i] = vertices[i];
        }
        vertices = temp;
    }

    public void add(PointHitBox p) {
        if (numVertices >= vertices.length - 1) {
            resize();
        }
        vertices[numVertices++] = p;
        vertices[numVertices] = vertices[0];
    }

    // Reference: http://exaflop.org/docs/cgafaq/cga2.html
    public boolean contains(PointHitBox p) {
        int crossings = 0;
        for (int i = 0; i < numVertices; i++) {
            int j = i + 1;
            boolean cond1 = (vertices[i].y <= p.y) && (p.y < vertices[j].y);
            boolean cond2 = (vertices[j].y <= p.y) && (p.y < vertices[i].y);
            if (cond1 || cond2) {
                if (p.x < (vertices[j].x - vertices[i].x) * (p.y - vertices[i].y) / (vertices[j].y - vertices[i].y) + vertices[i].x) {
                    crossings++;
                }
            }
        }
        if (crossings % 2 == 1) {
            return true;
        } else {
            return false;
        }
    }
}
